package com.hxx.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hxx.domain.TUser;
import com.hxx.service.UserService;
import com.hxx.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@WebServlet("*.do")
public class UserController extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String flag = "";
        TUser tUser = null;
        //获取json的数据
        String line = request.getReader().readLine();
        if (line!=null){
            tUser = JSON.parseObject(line,TUser.class);
            if (tUser!=null){
                flag = tUser.getFlag()!=null?tUser.getFlag():"";
            }
        }
        //根据flag判断是新增还是更新
        if ("add".equals(flag)){
            userService.save(tUser);
            return;
        }else if ("del".equals(flag)){
            userService.delete(tUser.getId());
            return;
        }else if ("update".equals(flag)){
            userService.update(tUser);
            return;
        }
        //获取分页信息
        JSONObject jsonObject = JSON.parseObject(line);
        int pageNo=1,pageSize=5;
        int rowCount = userService.rowCount();
        //如果有分页信息，则获取分页信息，否则使用默认值
        if (jsonObject.get("page")!=null){
            pageNo = Integer.valueOf(jsonObject.get("page").toString());
            pageSize = Integer.valueOf(jsonObject.get("size").toString());
        }
        //获取数据
        List<TUser> list = userService.findAll(pageNo,pageSize);
        //封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("rows",rowCount);
        //转换为json数据
        String json = JSON.toJSONString(map);
        //响应数据
        response.setContentType("text/html;charset=utf-8");
        //响应json数据
        response.getWriter().write(json);
    }
}
















































